<template>
    <div class="container">

        <!-- 基本搜索+功能按钮 -->
        <el-form ref="searchForm1" :inline="true" :model="searchForm" size="medium" label-width="">
            <div class="table_tool_bar_wrap">
                <div class="base_wrap mb10">
                    <div class="left">
                        <div>
                            <el-form-item label="交易类型" prop="status">
                                <el-radio-group v-model="searchForm.transactionType" @change="handleChangeTransactionType" size="small">
                                    <el-radio-button label="">全部</el-radio-button>
                                    <el-radio-button :label="1">推广佣金</el-radio-button>
                                    <el-radio-button :label="2">分销佣金</el-radio-button>
                                    <el-radio-button :label="3">会员提现</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                    </div>
                </div>
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="时间选择" prop="dateAttr">
                            <el-radio-group v-model="searchForm.dateAttr" @change="handleChangeDateAttr" size="small">
                                <el-radio-button label="">全部</el-radio-button>
                                <el-radio-button :label="0">今天</el-radio-button>
                                <el-radio-button :label="1">昨天</el-radio-button>
                                <el-radio-button :label="2">最近7天</el-radio-button>
                                <el-radio-button :label="3">最近30天</el-radio-button>
                                <el-radio-button :label="4">本月</el-radio-button>
                                <el-radio-button :label="5">本年</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="">
                            <el-date-picker
                                size="small"
                                v-model="dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd"
                                clearable
                                style="width: 280px">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </div>
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="快捷搜索" prop="keyword">
                            <el-input placeholder="" v-model="searchForm.keyword" clearable size="small"/>
                        </el-form-item>
                        <el-button @click="handleSearch" type="primary" size="small">搜索</el-button>
                        <el-button @click="handleReset" type="info" plain size="small">重置</el-button>
                        <el-button type="text" size="medium" @click="searchFlag = !searchFlag">
                            高级搜索<i class="el-icon--right" :class="searchFlag?'el-icon-arrow-down':'el-icon-arrow-up'"></i>
                        </el-button>
                    </div>
                </div>
            </div>
        </el-form>

        <!-- 高级搜索 -->
        <el-form class="mt10" ref="searchForm2" :inline="true" :model="searchForm" v-if="!searchFlag" size="medium" label-width="70px">
            <div class="table_tool_bar_wrap">
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="会员名称" prop="memberUsername">
                            <el-input placeholder="" v-model="searchForm.memberUsername" clearable size="small"/>
                        </el-form-item>
                        <el-form-item label="配送方式" prop="memberUsername">
                            <el-input placeholder="" v-model="searchForm.memberUsername" clearable size="small"/>
                        </el-form-item>

                        <el-form-item label="配送方式" prop="deliverType">
                            <el-select v-model="searchForm.deliverType" placeholder="请选择">
                                <el-option label="送货上门" :value="0" />
                                <el-option label="到店自提" :value="1" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </div>
        </el-form>

        <!-- 表格 -->
        <el-table
            class="mt10"
            ref="table"
            size="medium"
            height="500px"
            empty-text="暂无数据"
            element-loading-text="给我一点时间"
            fit border highlight-current-row
            show-summary
            :summary-method="getSummaries"
            :stripe="stripe"
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelection">

            <el-table-column type="selection" width="55" prop="selection" v-if="isHideColumn('selection')" align="center"></el-table-column>
            <el-table-column label="会员" prop="memberName" v-if="isHideColumn('memberName')" width="160" align="left" show-overflow-tooltip/>
            <el-table-column label="下级会员" prop="subMemberName" v-if="isHideColumn('subMemberName')" align="left" width="160" show-overflow-tooltip/>
            <el-table-column label="交易类型" prop="transactionType" v-if="isHideColumn('transactionType')" align="center" width="100">
                <template slot-scope="scope">
                    <div class="wrap">
                        <el-tag type="primary" size="small" v-if="scope.row.transactionType === 1">推广佣金</el-tag>
                        <el-tag type="danger" size="small" v-else-if="scope.row.transactionType === 2">分销佣金</el-tag>
                        <el-tag type="success" size="small" v-else-if="scope.row.transactionType === 3">提现</el-tag>
                        <el-tag type="info" size="small" v-else>-</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="交易金额（元）" prop="transactionAmount" align="left" width="180">
                <template slot-scope="scope">
                    <span style="color: #ff5722;">{{scope.row.transactionAmount}}</span>
                </template>
            </el-table-column>
            <el-table-column label="佣金比例" prop="commissionPercent" v-if="isHideColumn('commissionPercent')" width="160" align="left"/>
            <el-table-column label="备注" prop="remarks" v-if="isHideColumn('remarks')" align="left" show-overflow-tooltip/>
            <el-table-column label="交易时间" prop="ctime" v-if="isHideColumn('ctime')" width="160" align="left" show-overflow-tooltip/>

            <el-table-column label="操作" prop="btn" v-if="isHideColumn('btn')" width="200px" align="left" fixed="right">
                <template slot-scope="scope">
                    <el-button @click="handleAddOrUpdateVisible(scope.row.id)" type="text" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                    <el-button @click="handleDrawerVisible(scope.row)" type="text" size="small">详情</el-button>
                </template>
            </el-table-column>

        </el-table>

        <!-- 分页 -->
        <TablePagination
            :total.sync="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.limit"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"/>

        <!-- 弹窗, 新增 / 修改 -->
        <AddOrUpdate ref="addOrUpdate" @refreshDataList="getDataList"></AddOrUpdate>


        <!-- 同意 -->
        <el-dialog
            width="50%"
            title="同意申请"
            :visible.sync="agree.dialogVisible">

                <el-form ref="agree" :model="agree.data" :rules="rulesAgree" :inline="false" label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="会员名称" prop="name">
                                {{agree.info.name}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="会员手机号" prop="phone">
                                {{agree.info.phone}}
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="申请提现金额" prop="applyTakeAmount">
                        {{agree.info.applyTakeAmount}}
                    </el-form-item>

                    <el-form-item label="收取手续费" prop="commissionPercent">
                        <el-input v-model="agree.data.commissionPercent" type="number" @input="numberic100(agree.data,'commissionPercent',$event)" style="width:150px;"></el-input>
                    </el-form-item>

                </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="agree.dialogVisible = false">关 闭</el-button>
                <el-button @click="handleAgree" type="primary" :submitLoading="submitLoading">转 账</el-button>
            </div>
        </el-dialog>

        <!-- 拒绝申请 -->
        <el-dialog
            width="30%"
            title="拒绝申请"
            :visible.sync="reject.dialogVisible">


            <div slot="footer" class="dialog-footer">
                <el-button @click="reject.dialogVisible = false">关 闭</el-button>
                <el-button @click="handleReject" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>
        </el-dialog>


        <!-- 右侧抽屉,详情信息 -->
        <el-drawer
            ref="drawer"
            class="drawer_wrap"
            size="800px"
            :visible.sync="drawerVisible"
            :with-header="false"
            :modal="true"
            direction="rtl"
            :before-close="handleCloseDrawerDetail">
            <div class="header_title">
                <div class="title">详细</div>
                <div class="close el-icon-close" @click="$refs.drawer.closeDrawer()"></div>
            </div>

            <div class="header_body">
                <el-form :model="detail" :inline="false" label-width="120">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="姓名：">
                                {{detail.realname}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="姓名：">
                                {{detail.username}}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="OPENID：">
                        {{detail.openId}}
                    </el-form-item>
                    <el-form-item label="会员ID：">
                        {{detail.memberId}}
                    </el-form-item>
                    <el-form-item label="会员名称：">
                        {{detail.memberName}}
                    </el-form-item>
                    <el-form-item label="上级推广会员ID：">
                        {{detail.spreadId}}
                    </el-form-item>
                    <el-form-item label="上级推广会员名称：">
                        {{detail.spreadName}}
                    </el-form-item>
                    <el-form-item label="分销商品订单编号：">
                        {{detail.saleGoodsOrderSn}}
                    </el-form-item>
                    <el-form-item label="分销商品订单金额：">
                        {{detail.saleGoodsOrderAmount}}
                    </el-form-item>
                    <el-form-item label="交易金额：">
                        {{detail.transactionAmount}}
                    </el-form-item>
                    <el-form-item label="交易类型：1->推广佣金，2->分销佣金，3->提现：">
                        {{detail.transactionType}}
                    </el-form-item>
                    <el-form-item label="佣金比例：">
                        {{detail.commissionPercent}}
                    </el-form-item>
                    <el-form-item label="备注：">
                        {{detail.remarks}}
                    </el-form-item>
                    <el-form-item label="创建时间：">
                        {{detail.ctime}}
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>

    </div>
</template>

<script>
import TableMixin from '@/mixin/TableMixin'
import TableTools from '@/views/components/table/table-tools'
import TablePagination from '@/views/components/table/table-pagination'
import AddOrUpdate from './add-or-update-dialog'
import { numberic, numberic2, numberic100 } from "@/libs";
export default {
    mixins: [TableMixin],
    components: {
        TableTools,
        TablePagination,
        AddOrUpdate
    },

    data() {
        return {
            dataList: [],
            total: 0,
            loading: false,
            drawerVisible: false,
            selectionRows: [],
            searchFlag: true,
            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: null,
                sortType: null,
                keyword: null,
                openId: null,
                memberId: null,
                memberName: null,
                spreadId: null,
                spreadName: null,
                saleGoodsOrderSn: null,
                saleGoodsOrderAmount: null,
                transactionAmount: null,
                transactionType: '',
                dateRange: null,
                dateAttr: '',
            },
            dateRange: '',

            detail: {
                id: null,
                openId: null,
                memberId: null,
                memberName: null,
                spreadId: null,
                spreadName: null,
                saleGoodsOrderSn: null,
                saleGoodsOrderAmount: null,
                transactionAmount: null,
                transactionType: null,
                commissionPercent: null,
                remarks: null,
                ctime: null
            },

            submitLoading: false,

            // 同意申请
            agree: {
                dialogVisible: false,
                info: {},
                data: {
                    id: null,
                    commissionPercent: null,
                    commissionAmount: null,
                    factTakeAmount: null,
                }
            },

            rulesAgree: {
                commissionPercent: [
                    { required: true, message: '手续费不能为空', trigger: 'blur' }
                ]
            },

            // 拒绝申请
            reject: {
                dialogVisible: false,
                info: {},
                data: {
                    id: null,
                    commissionPercent: null,
                    commissionAmount: null,
                    factTakeAmount: null,
                }
            },

            numberic, numberic2, numberic100
        }
    },

    created() {
    },

    mounted() {
        this.$nextTick(() => {
            this.getDataList()
        })
    },

    methods: {

        /**
         * 侧边栏抽屉打开
         */
        handleDrawerVisible(row) {
            this.detail = row
            this.drawerVisible = true
        },

        /**
         * 新增或编辑
         */
        handleAddOrUpdateVisible(id) {
            // 表单窗口
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id)
            })
        },

        /**
         * 删除
         */
        async handleDelete(row) {
            let ids = []
            if (row) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {
                const confirm = await this.$confirm('确定要删除？', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/mall/fmsmembercashflow/delete',
                        method: 'POST',
                        data: ids
                    })
                    if (this.ResultMessage(res)) {
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 获取表格数据
         */
        async getDataList() {
            if(this.dateRange && this.dateRange.length > 0) {
                this.searchForm.dateAttr = ''
                this.searchForm.dateRange = this.dateRange.join(',')
            } else {
                this.searchForm.dateRange = null
            }

            this.loading = true
            const res = await this.$http({
                url: '/mall/fmsmembercashflow/page',
                method: 'GET',
                params: this.searchForm
            })
            if (this.ResultMessage(res, false)) {
                this.dataList = res.data.records || []
                this.total = res.data.total
            }
            this.loading = false
        },

        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index == 0) {
                    sums[index] = '总价';
                    return;
                }
                const values = data.map(
                    item =>
                    column.property === 'transactionAmount' ? Number(item[column.property]) : 0
                );
                if (!values.every(value => isNaN(value))
                    && (
                        column.property === 'transactionAmount'
                    )) {

                    let sumTotal = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);

                    sums[index] = sumTotal.toFixed(2) + ' 元'
                } else {
                    sums[index] = '';
                }
            });
            this.$nextTick(() => {
                this.$refs.table.doLayout();
            });
            return sums;
        },

        handleChangeDateAttr() {
            this.dateRange = null
            this.searchForm.dateRange = null
            this.getDataList()
        },
        handleChangeTransactionType() {
            this.getDataList()
        },


        /**
         * 同意申请窗口
         */
        handleAgreeVisible(row) {
            this.agree.info = row
            this.agree.data.id = row.id
            this.agree.dialogVisible = true
        },

        /**
         * 同意申请
         */
        async handleAgree() {
            const valid = await this.$refs.agree.validate().catch(() => {})
            console.log(valid);
            if(valid) {
                const confirm = await this.$confirm('确认拒绝收货？', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/mall/omsorderreturnapply/rejectGoods',
                        method: 'POST',
                        data: this.agree.data
                    })
                    if (this.ResultMessage(res)) {
                        this.agree.dialogVisible = false
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 拒绝申请窗口
         */
        handleRejectVisible(row) {
            this.reject.info = row
            this.reject.data.id = row.id
            this.reject.dialogVisible = true
        },

        /**
         * 拒绝申请
         */
        async handleReject() {
            const confirm = await this.$confirm('确认拒绝收货？', '提示', { type: 'warning' }).catch(() => {})
            if(confirm) {
                const res = await this.$http({
                    url: '/mall/omsorderreturnapply/rejectGoods',
                    method: 'POST',
                    data: this.reject.data
                })
                if (this.ResultMessage(res)) {
                    this.reject.dialogVisible = false
                    this.getDataList()
                }
            }
        },

        /**
         * 搜索
         */
        handleSearch() {
            this.getDataList()
        },
        /**
         * 重新加载数据表格
         */
        handleReload() {
            this.getDataList()
        },
        /**
         * 重置搜索表单
         */
        handleReset() {
            if(this.$refs.searchForm1) {
                this.$refs.searchForm1.resetFields()
            }
            if(this.$refs.searchForm2) {
                this.$refs.searchForm2.resetFields()
            }
        }

    }

}
</script>

<style lang="scss" scoped>

</style>
